/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Portions created by the Initial Developer are
 * Copyright (C) 2012 the Initial Developer.
 * All Rights Reserved.
 *
 * The Original Code is this.
 *
 * The Initial Developer of the Original Code is the author below.
 */
/**
 * @file TaskManager.h
 * @brief Manager of tasks.
 * @author K.Ozaki
 * @date 2011/12/21
 */

#ifndef TASKMANAGER_H_
#define TASKMANAGER_H_

#include <unistd.h>
#include "semi/MessageEvent.h"
#include "semi/SessionContext.h"

namespace semi {

/**
 * @brief Manager of tasks.
 *
 * @date 2011/12/21
 */
class TaskManager {
public:
    TaskManager();
    TaskManager(std::string taskId);
    virtual ~TaskManager();

    std::string taskId;
    std::string path;
    std::string args;

    void init(std::string taskId);
    void setValid();
    bool isValid();
    bool setWaitOn();
    bool setWaitOff();
    bool setTimerOn();
    bool setTimerOff();
    bool setPid();
    bool removePid();

    static void setAliveAll(conf::Configurator::TaskConfigs tconfs);
    static bool execute(std::string taskid);
    static bool shutdown(std::string tskId);
    static void executeAll(); // TODO TEST
    static void shutdown();

    // static void forceShutdown();

    static std::string toStringCurrentTasks(bool bl = false);

protected:
    semi::posix::SharedMemory mTasks;
    conf::Configurator::TaskConfig tConf;
    int index;

    static void setStopAll();

private:
    static std::string current_tasks_file_name;

    /// @brief task on use
    struct CurrentTask {
        char task_id[16]; // id
        char valid; // alive/kill
        char message_reserve; // reserve message
        char message_notify; // wait message
        int pid;
        int ppid;
        long long last;
    };
    struct CurrentTasks {
        CurrentTask tasks[128];
    };

    static bool execute(std::string taskid,
            conf::Configurator::TaskConfig taskcnf,
            semi::posix::SharedMemory currentTasks, int index);
    bool setMessageFlg(char timer, char notify);
    bool setPid(bool set);
    //    bool sweepChild();
};

}

#endif /* TASKMANAGER_H_ */
